import React from "react"
import StoreBuyView from "./StoreBuyView"
import { connect } from "react-redux"
import { bindActionCreators } from "redux"
import {withRouter} from 'react-router-dom';
import * as collectActions from '../../../../actions/collect'
// import * as collectActions from "../../../../actions/collect"

class StoreBuy extends React.Component {
    /**
     * 详情页视图页面 - >收藏与购买的业务逻辑 -> 收藏与购买的视图
     * 
     */

    constructor(){
        super();
        this.state = {
            collected:false
        }
    }

    componentDidMount(){
        // 设置收藏的值
        this.setState({
            collected:this.isCollected()
        })
    }
    isCollected = ()=>{
        return this.props.collection.some(element=>{
            return element=== this.props.id
        })
    }
    storeHandler(){
       /**
        * 判断是否登录,用户名为空，跳转到登录页面
        */
      if(this.props.isLogin){
        //   let isCollected = this.isCollected()
          this.setState({
            collected:!this.state.collected,
          },()=>{
            if(this.state.collected){
                this.props.collectActions.addCollection(this.props.id)
            }else{
                this.props.collectActions.removeCollection(this.props.id)
            }
          })
        
      }else{
          this.props.history.push('/login')
      }
    }

    /**
     * 收藏判断
     */

    // isStore() {
    //     // filter some every
    //     const id = this.props.id;
    //     const collects = this.props.collect;
    //     return collects.some((element) => {
    //         return element.id === id;
    //     })
    // }


    BuyHandler() {
        console.log("购买");
    }

    render() {
        return (
            <div>
                <StoreBuyView
                    collected={ this.state.collected }
                    onStoreHandler={this.storeHandler.bind(this)}
                    // onBuyHandler={this.BuyHandler.bind(this)}
                />
            </div>
        )
    }
}

const mapStateTopProps = (state)=>{
    return {
        isLogin:state.user.isLogin,
        collection:state.collection
    }
}

const mapDispatchToProps = (dispatch) => {
    return {
        collectActions:bindActionCreators(collectActions,dispatch)
    }
}
// function mapDispatchToProps(dispatch) {
//     return {
//         collectActions: bindActionCreators(collectActions, dispatch)
//     }
// }

export default connect(
    mapStateTopProps,
    mapDispatchToProps
)(withRouter(StoreBuy))